<?php
/*
	产品分类相关控制器
*/
namespace hotel\modules\api\controllers;


use hotel\common\models\Hotel;
use hotel\common\models\Comment;
use hotel\common\models\OrdersModel;
use hotel\common\models\Order;
use hotel\common\models\Promise;
use hotel\common\models\RoomType;
use hotel\common\models\RoomTypeActivity;
use hotel\common\models\RoomTypeActivityOff;
use hotel\common\models\RoomTypeOff;
use hotel\common\utils\AcServices;
use hotel\common\utils\CommonFun;
use hotel\common\utils\HotelServices;
use hotel\common\utils\MemberServices;
use hotel\common\utils\PayServices;
use hotel\common\utils\Tool;
use hotel\modules\apiadmin\models\HotelFacilitiesType;
use hotel\modules\apiadmin\models\RoomFacilitiesType;
use \Yii;
use yii\helpers\ArrayHelper;
use yii\log\FileTarget;

class HotelController extends CoreController
{
	//获取用户是否是酒店用户
	public function actionCheckPerson(){
		$get= \Yii::$app->request->get();
		if($get['phone']){
			$check = Order::find()
			->where(['phone'=>$get['phone']])
			//->andWhere(['<=','arr',date('Y-m-d 00:00:00',time())])
			->andWhere(['>=','dep',date('Y-m-d 00:00:00',time())])
			->asArray()->one();
			if($check)
				return Tool::showRes([0, '成功'], 1);
			else
				return Tool::showRes([0, '成功'], 2);
		}
		return Tool::showRes([400, '操作失败'], '缺少参数');
		
	}

    //获取酒店
    public function actionGetHotels()
    {

        $request = \Yii::$app->request;
        $post_data = $request->post();
        $comid = isset($post_data['comid']);
        if (empty($comid)) {
            return Tool::showRes([400, 'comid有误']);
        }
        $data = Hotel::find()->select(["a.*","b.is_place_order"])->from("hotel a")->leftJoin("su_common_app b", "a.appid = b.appid")
            ->where("b.comid = $comid")->asArray()->all();

        $type = isset($post_data['type']) ? $post_data['type'] : 1;
        $sort = isset($post_data['sort']) ? $post_data['sort'] : 'asc';
        $people_lat = $post_data['people_lat'];
        $people_lng = $post_data['people_lng'];
        foreach ($data as $k => $v) {
            //计算距离
            $coordinate_data = explode(',', $v['position']);
            if (!empty($people_lng) && !empty($people_lat) && !empty($coordinate_data[0]) && !empty($coordinate_data[1])) {
                if (!empty($coordinate_data)) {
                    $distance = $this->getDistance($people_lat, $people_lng, $coordinate_data[1], $coordinate_data[0]);
                } else {
                    $distance = 0;
                }
            } else {
                $distance = 0;
            }
            $data[$k]['distance'] = round($distance / 1000, 2);
            //计算上一次购房的时间差值
            $appid = $v['appid'];
            $order_data = OrdersModel::find()->where("appid = '$appid' and order_state = 2")->orderBy("id desc")->asArray()->one();
            $diff_minute = 0;
            if (!empty($order_data)) {
                $pay_time = strtotime($order_data['pay_time']);
                $diff_minute = floor((time() - $pay_time) / 60);
            }
            $data[$k]['diff_minute'] = $diff_minute;

        }
        if ($type == 2) {
            $order_str = 'distance';
            if ($sort == 'asc') {
                $sort = SORT_ASC;
            } elseif ($sort == 'desc') {
                $sort = SORT_DESC;
            }
            ArrayHelper::multisort($data, [$order_str], [$sort]);
        } elseif ($type == 3) {
            $order_str = 'starting_price';
            if ($sort == 'asc') {
                $sort = SORT_ASC;
            } elseif ($sort == 'desc') {
                $sort = SORT_DESC;
            }
            ArrayHelper::multisort($data, [$order_str], [$sort]);
        }
        return Tool::showRes([0, '获取酒店列表成功'], $data);
    }


    //获取酒店详情
    public function actionGetHotelDetail(){
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        if(empty($appid)){
            return Tool::showRes([400, 'appid有误']);
        }
        $data = Hotel::find()->asArray()->select(["a.*","b.is_place_order"])->from("hotel a")->leftJoin("su_common_app b", "a.appid = b.appid")->where("a.appid = '$appid'")->asArray()->one();
        $arr = [];
        if(!empty($data['hotel_facilities'])){
            $hotel_facilities = $data['hotel_facilities'];
            $hotel_facilities = explode(',',$hotel_facilities);
            foreach($hotel_facilities as $k=>$v){
                $hotel_facilities_id = $v;
                $res = HotelFacilitiesType::find()->where("id = $hotel_facilities_id")->asArray()->one();
                array_push($arr,$res);
            }
        }

        $data['banners'] = explode(',',$data['banners']);
        $data['hotel_facilities'] = $arr;
        return Tool::showRes([0, '获取酒店详情成功'], $data);
    }
    //获取房型
    public function actionGetRoomType()
    {

        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        if (empty($appid) || empty($arr) || empty($dep)) {
            return Tool::showRes([400, '参数有误']);
        }
        if (empty($appid)) {
            return Tool::showRes([400, 'appid有误']);
        }
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $res = $res['results'];
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                array_pop($res[$k]['dailyrates']);
                $rmtype = $v['rmtype'];
                $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
                $res[$k]['des'] = $room_type_data['des'];
                $res[$k]['appid'] = $room_type_data['appid'];
                $res[$k]['cover_image_url'] = $room_type_data['cover_image_url'];
                if (!empty($room_type_data['room_facilities'])) {
                    $room_type_facilities = $room_type_data['room_facilities'];
                    $room_type_facilities = json_decode($room_type_facilities, true);
                    $room_type_facilities_arr = [];
                    foreach ($room_type_facilities as $k1 => $v1) {
                        $room_type_facilities_id = $v1['id'];
                        $res1 = RoomFacilitiesType::find()->where("id = $room_type_facilities_id")->asArray()->one();
                        $res1['value'] = $v1['value'];
                        array_push($room_type_facilities_arr, $res1);
                    }
                    $res[$k]['room_facilities'] = $room_type_facilities_arr;
                } else {
                    $res[$k]['room_facilities'] = '';
                }
                $res[$k]['banners'] = explode(',', $room_type_data['banners']);
                $res[$k]['description'] = $room_type_data['description'];
                $res[$k]['reservation_rules'] = $room_type_data['reservation_rules'];
                $res[$k]['label'] = $room_type_data['label'];
                $res[$k]['is_place_order'] = $room_type_data['is_place_order'];
                $res[$k]['food'] = $room_type_data['food'];
                $res[$k]['entertainment'] = $room_type_data['entertainment'];
                $res[$k]['refund'] = $room_type_data['refund'];
                $res[$k]['gift'] = $room_type_data['gift'];
                $res[$k]['original_price'] = $room_type_data['original_price'];
                $res[$k]['discount_label'] = $room_type_data['discount_label'];
                $res[$k]['ticket_detail'] = $room_type_data['ticket_detail'];

                if($room_type_data['is_show'] == 2){
                    unset($res[$k]);
                }elseif($room_type_data['is_show'] == 1){
                    $room_type_id = $room_type_data['id'];
                    $date_arr = $this->periodDate($arr,$dep);
                    $temp_arr = [];
                    foreach($date_arr as $k2=>$v2){
                        $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->one();
                        if($room_type_off_res){
                            $temp_arr[$k2] = $room_type_off_res;
                        }
                    }
                    if($temp_arr){
                        unset($res[$k]);
                    }
                }
            }
        }
        ArrayHelper::multisort($res, ['rate'], [SORT_ASC]);

        return Tool::showRes([0, '获取房型成功'], $res);
    }

    //根据房型和日期获取每日价格
    public function actionGetDailyrates(){
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        $rmtype = $post_data['rmtype'];
        if (empty($appid) || empty($arr) || empty($dep)) {
            return Tool::showRes([400, '参数有误']);
        }
        if (empty($appid)) {
            return Tool::showRes([400, 'appid有误']);
        }
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $res = $res['results'];
        $arr = [];
        foreach($res as $k=>$v){
            if($v['rmtype'] == $rmtype){
                $arr = $v;
            }
        }
        return Tool::showRes([0, '获取每日价格成功'], $arr);
    }


    //提交订单
    public function actionPlaceOrder()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        if (empty($appid)) {
            return Tool::showRes([400, '参数有误']);
        }
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        $rmnum = $post_data['rmnum'];
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $room_type_res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $room_type_res = $room_type_res['results'];
        $rmtype = $post_data['rmtype'];
        $arr_temp = [];
        $total_price = 0;
        foreach ($room_type_res as $k => $v) {
            if ($v['rmtype'] == $rmtype) {
                array_push($arr_temp, $v);
            }
        }

        //判断该时间范围能否下单
        $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
        $room_type_id = $room_type_data['id'];
        $date_arr = $this->periodDate($arr, $dep);
        $temp_arr22 = [];
        foreach ($date_arr as $k2 => $v2) {
            $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->asArray()->one();
            if ($room_type_off_res) {
                $temp_arr22[$k2] = $room_type_off_res;
            }
        }
        if ($temp_arr22) {
            return Tool::showRes([400, '该时间范围不能下单']);
        }




        if ($arr_temp[0]['avail'] < $rmnum) {
            return Tool::showRes([400, '剩余房量不足']);
        }
        array_pop($arr_temp[0]['dailyrates']);
        foreach ($arr_temp[0]['dailyrates'] as $k => $v) {
            $total_price = $total_price + $v['rate'];
        }
        //乘以天数
        $total_price = $total_price * $post_data['rmnum'];
        $extra['kly_member_id'] = isset($post_data['kly_member_id'])?$post_data['kly_member_id']:'';
        //恐龙园专属优惠券参数 1-恐龙园 2-认证中心
        if($post_data['coupon_from'] == 1){
            $extra['coupon_info']['coupons_type'] = isset($post_data['coupons_type'])?$post_data['coupons_type']:'';
            $extra['coupon_info']['couponid'] = isset($post_data['couponid'])?$post_data['couponid']:'';
            $extra['coupon_info']['couponname'] = isset($post_data['couponname'])?$post_data['couponname']:'';
            $extra['coupon_info']['discount'] = isset($post_data['discount'])?$post_data['discount']:'';
            $extra['guding_discount'] = isset($post_data['guding_discount'])?$post_data['guding_discount']:1;
            $extra['coupon_info']['coupon_from'] = $post_data['coupon_from'];

        }elseif($post_data['coupon_from'] == 2){
            $extra['coupon_info']['coupons_type'] = isset($post_data['coupons_type'])?$post_data['coupons_type']:'';
            $extra['coupon_info']['couponid'] = isset($post_data['couponid'])?$post_data['couponid']:'';
            $extra['coupon_info']['couponname'] = isset($post_data['couponname'])?$post_data['couponname']:'';
            $extra['coupon_info']['discount'] = isset($post_data['discount'])?$post_data['discount']:'';
            $extra['coupon_info']['coupon_from'] = $post_data['coupon_from'];
        }

        //恐龙园优惠券参数
        if($extra['coupon_info']['coupon_from'] == 1){
            if($extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid']  && $extra['coupon_info']['discount']){
                $coupons_type = $extra['coupon_info']['coupons_type'];
                if ($coupons_type == 1) {
                    $discount_column = isset($extra['coupon_info']['discount']) ? (($extra['coupon_info']['discount']) / 100) : 1;
                    if ($discount_column) {
                        $pay_price = ($total_price * $extra['guding_discount']) * $discount_column;
                        $discount = $total_price- $pay_price;
                    }
                }
                if ($coupons_type == 2 || $coupons_type == 3) {
                    $coupon_discount = isset($extra['coupon_info']['discount']) ? $extra['coupon_info']['discount'] : 0;
                    $pay_price = $total_price * $extra['guding_discount'] - $coupon_discount;
                    if($pay_price < 0 ){
                        $pay_price = 0;
                    }
                    $discount = $total_price- $pay_price;
                }
                $pay_price = sprintf('%.2f', $pay_price);
                if($pay_price < 0){
                    return [400,'金额有误'];
                }
            }else{
                $pay_price = $total_price* $extra['guding_discount'];
                $pay_price = sprintf('%.2f', $pay_price);
                $cartGoods['discount'] = $total_price - $pay_price;
                $cartGoods['pay_price'] = $pay_price ;;
            }
        }elseif($extra['coupon_info']['coupon_from'] == 2){
            //除了恐龙园和德清的生成订单
            if($extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid']  && $extra['coupon_info']['discount']){
                $coupons_type = $extra['coupon_info']['coupons_type'];
                if ($coupons_type == 2) {
                    $discount_column = isset($extra['coupon_info']['discount']) ? (($extra['coupon_info']['discount']) / 100) : 1;
                    if ($discount_column) {
                        $pay_price = $total_price  * $discount_column;
                        $discount = $total_price- $pay_price;
                    }
                }
                if ($coupons_type == 1 || $coupons_type == 3) {
                    $coupon_discount = isset($extra['coupon_info']['discount']) ? $extra['coupon_info']['discount'] : 0;
                    $pay_price = $total_price - $coupon_discount;
                    if($pay_price < 0 ){
                        $pay_price = 0;
                    }
                    $discount = $total_price- $pay_price;
                }
                $pay_price = sprintf('%.2f', $pay_price);
                if($pay_price < 0){
                    return [400,'金额有误'];
                }
                $cartGoods['pay_price'] = $pay_price;
                $cartGoods['discount'] = $discount;
            }else{
                $pay_price = $total_price;
                $pay_price = sprintf('%.2f', $pay_price);
                $cartGoods['pay_price'] = $pay_price;
                $cartGoods['discount'] = 0;
            }
        }
        $transaction = Yii::$app->db->beginTransaction();


        //保存订单到数据库
        $order_sn = CommonFun::makeRandSn($this->member_id);
        $model = New OrdersModel();
        $model->appid = $appid;
        $model->member_id = $this->member_id;
        $model->order_sn = $order_sn;
        $model->price = $total_price;
        $model->pay_price = $pay_price;
        $model->name = $post_data['name'];
        $model->phone = $post_data['phone'];
        $model->ratecode = $post_data['ratecode'];
        $model->rmtype = $post_data['rmtype'];
        $model->des = $post_data['des'];
        $model->rate = $post_data['rate'];
        $model->rmnum = $post_data['rmnum'];
        $model->arr = $post_data['arr'];
        $model->dep = $post_data['dep'];
        $model->pkg = $post_data['pkg'];
        $model->kly_member_id = $extra['kly_member_id'];
        $model->discount = $discount;
        $model->coupons_type = $extra['coupon_info']['coupons_type'];
        $model->couponid = $extra['coupon_info']['couponid'];
        $model->couponname = $extra['coupon_info']['couponname'];
        $model->coupon_from = $extra['coupon_info']['coupon_from'];
        $model->order_ddetail = json_encode($arr_temp[0]['dailyrates']);
        $model->order_state = 1;
        $model->payment_code = isset($post_data['pay_type'])?$post_data['pay_type']:'weixin';

        $model->create_time = date('Y-m-d H:i:s');
        if ($model->save()) {
            $orderId = $model->attributes['id'];
            //核销优惠券（恐龙园优惠券核销）
            if($extra['coupon_info']['coupon_from'] == 1 && $extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid']  && $extra['coupon_info']['discount']){
                $res = MemberServices::verify($extra['kly_member_id'],$extra['coupon_info']['couponid'],$extra['coupon_info']['couponname'],$orderId,$appid);
                if(!$res){
                    $transaction->rollBack();
                    return Tool::showRes([400, '核销优惠券失败']);
                }
            }
            //核销优惠券（认证中心优惠券核销）
            if($extra['coupon_info']['coupon_from'] == 2 && $extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid']  && $extra['coupon_info']['discount']){
                $res = AcServices::useCoupon($appid,$this->member_id,$extra['coupon_info']['couponid']);
                if(!$res){
                    $transaction->rollBack();
                    return Tool::showRes([400, '核销优惠券失败']);
                }
            }
            $transaction->commit();
            return Tool::showRes([0, '下单成功'], $order_sn);
        } else {

            return Tool::showRes([400, '下单失败']);
        }
    }
//判断是否可以选择
    public function actionCheckRoomTypeOff()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        if (empty($appid)) {
            return Tool::showRes([400, '参数有误']);
        }
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        $rmtype = $post_data['rmtype'];
        $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
        $room_type_id = $room_type_data['id'];
        $date_arr = $this->periodDate($arr, $dep);
        $temp_arr = [];
        foreach ($date_arr as $k2 => $v2) {
            $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->asArray()->one();
            if ($room_type_off_res) {
                $temp_arr[$k2] = $room_type_off_res;
            }
        }
        if ($temp_arr) {
            return Tool::showRes([400, '不能选取当前时间范围'],$temp_arr);
        }
        return Tool::showRes([0, '可以选取']);
    }

    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    //根据订单获取订单详情
    public function actionGetOrderDetail()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->select(['a.*', 'b.cover_image_url', 'b.des'])
            ->from("order a")->leftJoin("room_type b", "a.rmtype = b.rmtype")
            ->where("order_sn = '$order_sn'")->asArray()->one();
        $pay_day = substr($order_data['pay_time'], 0, 10);
        if ($pay_day == date('Y-m-d') && $order_data['order_state'] == 2) {
            $order_data['is_show_refund'] = 1;
        } else {
            $order_data['is_show_refund'] = 0;
        }
        $arr_day = $this->rn_date($order_data['arr']);
        $dep_day = $this->rn_date($order_data['dep']);
        $diff = $this->diffBetweenTwoDays(substr($order_data['arr'], 0, 10), substr($order_data['dep'], 0, 10));
        $order_data['diff'] = $arr_day . '——' . $dep_day . ',共' . $diff . '晚';
        return Tool::showRes([0, '获取订单详情成功'], $order_data);
    }

    //支付
    public function actionPay()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单号有误']);
        }

        if ($order_data['price'] != 0) {
            //获取每日房价
            $session = HotelServices::checkXopSession($order_data['appid']);
            $room_type_res = HotelServices::xopratequery($session, $order_data['appid'], $order_data['arr'], $order_data['dep']);
            $room_type_res = $room_type_res['results'];
            $rmtype = $order_data['rmtype'];
            $arr_temp = [];
            foreach ($room_type_res as $k => $v) {
                if ($v['rmtype'] == $rmtype) {
                    array_push($arr_temp, $v);
                }
            }
            if ($arr_temp[0]['avail'] < $order_data['rmnum']) {
                return Tool::showRes([400, '剩余房量不足,无法支付']);
            }
            $res = PayServices::Pay($this->openid, $order_data['pay_price'] * 100, $order_data['order_sn'], '酒店', '酒店', $order_data['appid']);
            if ($res) {
                return Tool::showRes([0, '拉起支付成功'], $res);
            } else {
                return Tool::showRes([400, '拉起支付失败']);
            }
        } else {
            return Tool::showRes([400, '订单金额有误']);
        }

    }


    //支付
    public function actionPay1()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单号有误']);
        }

        if ($order_data['price'] != 0) {
            //获取每日房价
            $session = HotelServices::checkXopSession($order_data['appid']);
            $room_type_res = HotelServices::xopratequery($session, $order_data['appid'], $order_data['arr'], $order_data['dep']);
            $room_type_res = $room_type_res['results'];
            $rmtype = $order_data['rmtype'];
            $arr_temp = [];
            foreach ($room_type_res as $k => $v) {
                if ($v['rmtype'] == $rmtype) {
                    array_push($arr_temp, $v);
                }
            }
            if ($arr_temp[0]['avail'] < $order_data['rmnum']) {
                return Tool::showRes([400, '剩余房量不足,无法支付']);
            }
            $res = PayServices::Pay1($this->openid, $order_data['pay_price'] * 100, $order_data['order_sn'], '酒店', '酒店', $order_data['appid']);
            if ($res) {
                return Tool::showRes([0, '拉起支付成功'], $res);
            } else {
                return Tool::showRes([400, '拉起支付失败']);
            }
        } else {
            return Tool::showRes([400, '订单金额有误']);
        }

    }

    //支付
    public function actionAliPay()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $ali_user_id = $post_data['ali_user_id'];

        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单号有误']);
        }

        if ($order_data['price'] != 0) {
            //获取每日房价
            $session = HotelServices::checkXopSession($order_data['appid']);
            $room_type_res = HotelServices::xopratequery($session, $order_data['appid'], $order_data['arr'], $order_data['dep']);
            $room_type_res = $room_type_res['results'];
            $rmtype = $order_data['rmtype'];
            $arr_temp = [];
            foreach ($room_type_res as $k => $v) {
                if ($v['rmtype'] == $rmtype) {
                    array_push($arr_temp, $v);
                }
            }
            if ($arr_temp[0]['avail'] < $order_data['rmnum']) {
                return Tool::showRes([400, '剩余房量不足,无法支付']);
            }
            $res = PayServices::AliPay($ali_user_id, $order_data['pay_price'] * 100, $order_data['order_sn'], '酒店', '酒店', $order_data['appid']);
            if ($res) {
                return Tool::showRes([0, '拉起支付成功'], $res);
            } else {
                return Tool::showRes([400, '拉起支付失败']);
            }
        } else {
            return Tool::showRes([400, '订单金额有误']);
        }

    }

    //取消订单
    public function actionCancelOrder()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = '$order_sn'")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单号有误']);
        }
        if ($order_data['order_state'] != 1) {
            return Tool::showRes([400, '订单号状态不能取消']);
        }
        //更新订单
        $data = array(
            'order_state' => 0,
        );
        $transaction = Yii::$app->db->beginTransaction();

        $flag = OrdersModel::updateAll($data, ['order_sn' => $order_sn]);
        if ($flag) {
            //退回优惠券（1-恐龙园 2-认证中心）
            if($order_data['coupon_from'] == 1 && !empty($order_data['couponid'] && !empty($order_data['couponname']))){
                $res = MemberServices::cancel($order_data['kly_member_id'],$order_data['couponid'],$order_data['couponname'],$order_data['order_id'],$order_data['appid']);
                if(!$res){
                    $transaction->rollBack();
                    return Tool::showRes([400, '核销优惠券失败']);
                }
            }elseif($order_data['coupon_from'] == 2 && !empty($order_data['couponid'] && !empty($order_data['couponname']))){

            }
            $transaction->commit();
            return Tool::showRes([0, '订单取消成功']);
        } else {
            $transaction->rollBack();
            return Tool::showRes([400, '订单取消失败']);
        }
    }

    //我的酒店订单列表
    public function actionOrderList()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $type = isset($post_data['type']) ? $post_data['type'] : 1;
        $page = isset($post_data['page']) ? $post_data['page'] : 1;
        $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
        if ($type == 1) {
            $pages = OrdersModel::find()->where("member_id = '$this->member_id' and  order_state = 1")->count();
            $data = OrdersModel::find()
                ->select(['a.*', 'b.cover_image_url'])
                ->from("order a")
                ->leftJoin("room_type b", "a.rmtype = b.rmtype")
                ->offset($limit * ($page - 1))
                ->where("member_id = '$this->member_id' and order_state = 1")
                ->orderBy("id desc")
                ->limit($limit)
                ->asArray()->all();

            $res['list'] = $data;
            $res['pageInfo'] = [
                'count' => $pages,
                'pageSize' => $limit,
                'currPage' => $page,
                'tatalPage' => ceil($pages / $limit),
            ];
        } elseif ($type == 2) {
            $pages = OrdersModel::find()->where("member_id = '$this->member_id' and  order_state = 2")->count();
            $data = OrdersModel::find()
                ->select(['a.*', 'b.cover_image_url'])
                ->from("order a")
                ->leftJoin("room_type b", "a.rmtype = b.rmtype")
                ->offset($limit * ($page - 1))
                ->where("member_id = '$this->member_id' and order_state = 2")
                ->orderBy("id desc")
                ->limit($limit)
                ->asArray()->all();
				foreach($data as $k=>$v){
					$comment = Comment::find()->where(['order_id'=>$v['id']])->asArray()->one();
					$data[$k]['is_comment'] = $comment?2:1;
				}
            $res['list'] = $data;
            $res['pageInfo'] = [
                'count' => $pages,
                'pageSize' => $limit,
                'currPage' => $page,
                'tatalPage' => ceil($pages / $limit),
            ];
        } elseif ($type == 3) {
            $pages = OrdersModel::find()->where("member_id = '$this->member_id' and  order_state = 3")->count();
            $data = OrdersModel::find()
                ->select(['a.*', 'b.cover_image_url'])
                ->from("order a")
                ->leftJoin("room_type b", "a.rmtype = b.rmtype")
                ->offset($limit * ($page - 1))
                ->where("member_id = '$this->member_id' and order_state = 3")
                ->orderBy("id desc")
                ->limit($limit)
                ->asArray()->all();
            $res['list'] = $data;
            $res['pageInfo'] = [
                'count' => $pages,
                'pageSize' => $limit,
                'currPage' => $page,
                'tatalPage' => ceil($pages / $limit),
            ];
        }
        return Tool::showRes([0, '获取我的订单列表成功'], $res);

    }


    //退款
    public function actionRefund()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if ($order_data['order_state'] != 2) {
            return Tool::showRes([400, '订单状态有误，无法退款']);
        }
        $pay_day = substr($order_data['pay_time'], 0, 10);
        if ($pay_day != date('Y-m-d')) {
            return Tool::showRes([400, '只能退款当天付款的订单哦']);
        }
        $session = HotelServices::checkXopSession($order_data['appid']);
        $res = HotelServices::xopwriteoffpayaccount($session, $order_data['appid'], $order_data);
        if ($res['success'] == 1) {
            //更新订单
            $data = array(
                'opx_state' => 4,
            );
            OrdersModel::updateAll($data, ['order_sn' => $order_data['order_sn']]);

            $res1 = HotelServices::xopcxlreservation($session, $order_data['appid'], $order_data);
            if ($res1['success'] == 1) {
                //更新订单
                $data = array(
                    'opx_state' => 5,
                );
                OrdersModel::updateAll($data, ['order_sn' => $order_data['order_sn']]);
                $res = PayServices::refundOrder($order_data['member_id'], $order_data['pay_price'] * 100, $order_data['order_sn'], $order_data['pay_price'] * 100, $order_data['appid']);
                if ($res['code'] == 0) {
                    //更新订单
                    $data = array(
                        'order_state' => 3,
                    );
                    $flag = OrdersModel::updateAll($data, ['order_sn' => $order_data['order_sn']]);
                    if ($flag) {
                        return Tool::showRes([0, '退款成功']);
                    } else {
                        return Tool::showRes([400, '退款失败']);
                    }
                } else {
                    return Tool::showRes([400, '退款失败']);
                }
            } else {
                return Tool::showRes([400, '取消订单失败']);
            }
        } else {
            return Tool::showRes([400, '预付入账冲销失败']);
        }
    }


    //西软查询订单
    public function actionCheckOrder()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单不存在']);
        }
        $session = HotelServices::checkXopSession($order_data['appid']);
        $res = HotelServices::xopqueryreservation($session, $order_data['appid'], $order_data);
        return Tool::showRes([0, '查询订单'], $res);

    }

    //西软取消订单
    public function actionXopCancelOrder()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $order_sn = $post_data['order_sn'];
        $order_data = OrdersModel::find()->where("order_sn = $order_sn")->asArray()->one();
        if (empty($order_data)) {
            return Tool::showRes([400, '订单不存在']);
        }
        $session = HotelServices::checkXopSession($order_data['appid']);
        $res = HotelServices::xopcxlreservation($session, $order_data['appid'], $order_data);
        return Tool::showRes([0, '查询订单'], $res);

    }
    //承诺书
    public function actionPromise()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $this->recordData(json_encode($post_data));
        $appid = $post_data['appid'];
        if (empty($appid)) {
            return Tool::showRes([400, '参数有误']);
        }
        $name = $post_data['name'];
        $openid = $post_data['openid'];
        $phone = $post_data['phone'];
        $id_card = $post_data['id_card'];
        $date = $post_data['date'];
        $room_num = $post_data['room_num'];
        $img_url = $post_data['img_url'];
        $model = New Promise();
        $model->appid = $appid;
        $model->name = $name;
        $model->openid = $openid;
        $model->phone = $phone;
        $model->id_card = $id_card;
        $model->date = $date;
        $model->room_num = $room_num;
        $model->img_url = $img_url;
        $model->create_time = date('Y-m-d h:i:s');
        if ($model->save()) {
            return Tool::showRes([0, '记录成功']);
        } else {
            return Tool::showRes([400, '记录失败']);
        }
    }

    //承诺书
    public function actionGetPromise()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $this->recordData(json_encode($post_data));
        $openid = $post_data['openid'];
        if (empty($openid)) {
            return Tool::showRes([400, '参数有误']);
        }
        $last_time = date('Y-m-d H:i:s',time()-3600*24*14);
        // $data = Promise::find()->where("openid = '$openid' and create_time >'$last_time'")->orderby('id desc')->asArray()->one();
        $data = Promise::find()->where('openid = :oid',[':oid' => $openid])->andWhere(['>','create_time',$last_time])->orderby('id desc')->asArray()->one();
        if($data){
            return Tool::showRes([0, '查询承诺书成功'], $data);
        }else{
            return Tool::showRes([400, '14天内暂无承诺书']);
        }
    }

    public function actionGetRoomType1()
    {

        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        if (empty($appid) || empty($arr) || empty($dep)) {
            return Tool::showRes([400, '参数有误']);
        }
        if (empty($appid)) {
            return Tool::showRes([400, 'appid有误']);
        }
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $res = $res['results'];
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                if ($v['ratecode'] == 'FDRK') {
                    array_pop($res[$k]['dailyrates']);
                    $res[$k]['old_rate'] = $v['rate'];

                    //判断是否有参与活动优惠
                    foreach ($res[$k]['dailyrates'] as $k9 => $v9) {
                        $res9 = $this->actionCheckRoomTypeActivity($v9['date'], $v9['rate'], $v['rmtype']);
                        $res[$k]['dailyrates'][$k9]['rate'] = sprintf("%01.1f", $res9['rate']);
                        $res[$k]['dailyrates'][$k9]['label'] = $res9['label'];
                        $res[$k]['dailyrates'][$k9]['type'] = $res9['type'];
                        $res[$k]['dailyrates'][$k9]['num'] = $res9['num'];

                    }
                    $res[$k]['rate'] = sprintf("%01.1f", $res[$k]['dailyrates'][0]['rate']);
                    $res[$k]['activity_label'] = $res[$k]['dailyrates'][0]['label'];
                    $res[$k]['type'] = $res[$k]['dailyrates'][0]['type'];
                    $res[$k]['num'] = $res[$k]['dailyrates'][0]['num'];

                    $rmtype = $v['rmtype'];
                    $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
                    $res[$k]['des'] = $room_type_data['des'];
                    $res[$k]['appid'] = $room_type_data['appid'];
                    $res[$k]['cover_image_url'] = $room_type_data['cover_image_url'];
                    if (!empty($room_type_data['room_facilities'])) {
                        $room_type_facilities = $room_type_data['room_facilities'];
                        $room_type_facilities = json_decode($room_type_facilities, true);
                        $room_type_facilities_arr = [];
                        foreach ($room_type_facilities as $k1 => $v1) {
                            $room_type_facilities_id = $v1['id'];
                            $res1 = RoomFacilitiesType::find()->where("id = $room_type_facilities_id")->asArray()->one();
                            $res1['value'] = $v1['value'];
                            array_push($room_type_facilities_arr, $res1);
                        }
                        $res[$k]['room_facilities'] = $room_type_facilities_arr;
                    } else {
                        $res[$k]['room_facilities'] = '';
                    }
                    $res[$k]['banners'] = explode(',', $room_type_data['banners']);
                    $res[$k]['description'] = $room_type_data['description'];
                    $res[$k]['reservation_rules'] = $room_type_data['reservation_rules'];
                    $res[$k]['label'] = $room_type_data['label'];
                    $res[$k]['is_place_order'] = $room_type_data['is_place_order'];
                    $res[$k]['food'] = $room_type_data['food'];
                    $res[$k]['entertainment'] = $room_type_data['entertainment'];
                    $res[$k]['refund'] = $room_type_data['refund'];
                    $res[$k]['gift'] = $room_type_data['gift'];
                    $res[$k]['original_price'] = $room_type_data['original_price'];
                    $res[$k]['discount_label'] = $room_type_data['discount_label'];

                    if ($room_type_data['is_show'] == 2) {
                        unset($res[$k]);
                    } elseif ($room_type_data['is_show'] == 1) {
                        $room_type_id = $room_type_data['id'];
                        $date_arr = $this->periodDate($arr, $dep);
                        $temp_arr = [];
                        foreach ($date_arr as $k2 => $v2) {
                            $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->one();
                            if ($room_type_off_res) {
                                $temp_arr[$k2] = $room_type_off_res;
                            }
                        }
                        if ($temp_arr) {
                            unset($res[$k]);
                        }
                    }
                }else{
                    unset($res[$k]);
                }
            }
        }

        ArrayHelper::multisort($res, ['rate'], [SORT_ASC]);

        return Tool::showRes([0, '获取房型成功'], $res);
    }

    public function actionGetJjRoomType()
    {

        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        if (empty($appid) || empty($arr) || empty($dep)) {
            return Tool::showRes([400, '参数有误']);
        }
        if (empty($appid)) {
            return Tool::showRes([400, 'appid有误']);
        }
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $res = $res['results'];
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                if ($v['ratecode'] == 'XCXJJ') {
                    array_pop($res[$k]['dailyrates']);
                    $res[$k]['old_rate'] = $v['rate'];

                    //判断是否有参与活动优惠
                    foreach ($res[$k]['dailyrates'] as $k9 => $v9) {
                        $res9 = $this->actionCheckRoomTypeActivity($v9['date'], $v9['rate'], $v['rmtype']);
                        $res[$k]['dailyrates'][$k9]['rate'] = sprintf("%01.1f", $res9['rate']);
                        $res[$k]['dailyrates'][$k9]['label'] = $res9['label'];
                        $res[$k]['dailyrates'][$k9]['type'] = $res9['type'];
                        $res[$k]['dailyrates'][$k9]['num'] = $res9['num'];

                    }
                    $res[$k]['rate'] = sprintf("%01.1f", $res[$k]['dailyrates'][0]['rate']);
                    $res[$k]['activity_label'] = $res[$k]['dailyrates'][0]['label'];
                    $res[$k]['type'] = $res[$k]['dailyrates'][0]['type'];
                    $res[$k]['num'] = $res[$k]['dailyrates'][0]['num'];

                    $rmtype = $v['rmtype'];
                    $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
                    $res[$k]['des'] = $room_type_data['des'];
                    $res[$k]['appid'] = $room_type_data['appid'];
                    $res[$k]['cover_image_url'] = $room_type_data['cover_image_url'];
                    if (!empty($room_type_data['room_facilities'])) {
                        $room_type_facilities = $room_type_data['room_facilities'];
                        $room_type_facilities = json_decode($room_type_facilities, true);
                        $room_type_facilities_arr = [];
                        foreach ($room_type_facilities as $k1 => $v1) {
                            $room_type_facilities_id = $v1['id'];
                            $res1 = RoomFacilitiesType::find()->where("id = $room_type_facilities_id")->asArray()->one();
                            $res1['value'] = $v1['value'];
                            array_push($room_type_facilities_arr, $res1);
                        }
                        $res[$k]['room_facilities'] = $room_type_facilities_arr;
                    } else {
                        $res[$k]['room_facilities'] = '';
                    }
                    $res[$k]['banners'] = explode(',', $room_type_data['banners']);
                    $res[$k]['description'] = $room_type_data['description'];
                    $res[$k]['reservation_rules'] = $room_type_data['reservation_rules'];
                    $res[$k]['label'] = $room_type_data['label'];
                    $res[$k]['is_place_order'] = $room_type_data['is_place_order'];
                    $res[$k]['food'] = $room_type_data['food'];
                    $res[$k]['entertainment'] = $room_type_data['entertainment'];
                    $res[$k]['refund'] = $room_type_data['refund'];
                    $res[$k]['gift'] = $room_type_data['gift'];
                    $res[$k]['original_price'] = $room_type_data['original_price'];
                    $res[$k]['discount_label'] = $room_type_data['discount_label'];

                    if ($room_type_data['is_show'] == 2) {
                        unset($res[$k]);
                    } elseif ($room_type_data['is_show'] == 1) {
                        $room_type_id = $room_type_data['id'];
                        $date_arr = $this->periodDate($arr, $dep);
                        $temp_arr = [];
                        foreach ($date_arr as $k2 => $v2) {
                            $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->one();
                            if ($room_type_off_res) {
                                $temp_arr[$k2] = $room_type_off_res;
                            }
                        }
                        if ($temp_arr) {
                            unset($res[$k]);
                        }
                    }
                }else{
                    unset($res[$k]);
                }
            }
        }

        ArrayHelper::multisort($res, ['rate'], [SORT_ASC]);

        return Tool::showRes([0, '获取房型成功'], $res);
    }

    //根据房型和日期获取每日价格
    public function actionGetDailyrates1()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        $rmtype = $post_data['rmtype'];
        $type = isset($post_data['type'])?$post_data['type']:1;

        if (empty($appid) || empty($arr) || empty($dep)) {
            return Tool::showRes([400, '参数有误']);
        }
        if (empty($appid)) {
            return Tool::showRes([400, 'appid有误']);
        }
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $res = $res['results'];
        $arr = [];
        if($type == 1){
            foreach ($res as $k => $v) {
                if($v['ratecode'] == 'FDRK') {
                    //判断是否有参与活动优惠
                    foreach ($res[$k]['dailyrates'] as $k9 => $v9) {
                        $res9 = $this->actionCheckRoomTypeActivity($v9['date'], $v9['rate'], $v['rmtype']);
                        $res[$k]['dailyrates'][$k9]['rate'] = sprintf("%01.1f", $res9['rate']);;
                    }
                    $res[$k]['rate'] = $res[$k]['dailyrates'][0]['rate'];

                    if ($v['rmtype'] == $rmtype) {
                        $arr = $res[$k];
                    }
                }
            }
        }else{
            foreach ($res as $k => $v) {
                if($v['ratecode'] == 'XCXJJ') {
                    //判断是否有参与活动优惠
                    foreach ($res[$k]['dailyrates'] as $k9 => $v9) {
                        $res9 = $this->actionCheckRoomTypeActivity($v9['date'], $v9['rate'], $v['rmtype']);
                        $res[$k]['dailyrates'][$k9]['rate'] = sprintf("%01.1f", $res9['rate']);;
                    }
                    $res[$k]['rate'] = $res[$k]['dailyrates'][0]['rate'];

                    if ($v['rmtype'] == $rmtype) {
                        $arr = $res[$k];
                    }
                }
            }
        }

        return Tool::showRes([0, '获取每日价格成功'], $arr);
    }
    //提交订单
    public function actionPlaceOrder1()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $appid = $post_data['appid'];
        if (empty($appid)) {
            return Tool::showRes([400, '参数有误']);
        }
        $arr = $post_data['arr'];
        $dep = $post_data['dep'];
        $rmnum = $post_data['rmnum'];
        $session = HotelServices::checkXopSession($appid);
        //获取每日房价
        $room_type_res = HotelServices::xopratequery($session, $appid, $arr, $dep);
        $room_type_res = $room_type_res['results'];
        $rmtype = $post_data['rmtype'];

        //判断该时间范围能否下单
        $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
        $room_type_id = $room_type_data['id'];
        $date_arr = $this->periodDate($arr, $dep);
        $temp_arr22 = [];
        foreach ($date_arr as $k2 => $v2) {
            $room_type_off_res = RoomTypeOff::find()->where("date = '$v2' and room_type_id = $room_type_id")->asArray()->one();
            if ($room_type_off_res) {
                $temp_arr22[$k2] = $room_type_off_res;
            }
        }
        if ($temp_arr22) {
            return Tool::showRes([400, '该时间范围不能下单']);
        }



        $arr_temp = [];
        $total_price = 0;
        foreach ($room_type_res as $k => $v) {
            if ($v['rmtype'] == $rmtype && $v['ratecode'] == $post_data['ratecode']) {
                array_push($arr_temp, $v);
            }
        }
        if ($arr_temp[0]['avail'] < $rmnum) {
            return Tool::showRes([400, '剩余房量不足']);
        }

        array_pop($arr_temp[0]['dailyrates']);
        foreach ($arr_temp[0]['dailyrates'] as $k => $v) {
            //判断是否有参与活动优惠
            $res = $this->actionCheckRoomTypeActivity($v['date'], $v['rate'], $rmtype);
            $arr_temp[0]['dailyrates'][$k]['rate'] = $res['rate'];
            $total_price = $total_price + $res['rate'];
        }
        //乘以天数
        $total_price = $total_price * $post_data['rmnum'];
        $extra['kly_member_id'] = isset($post_data['kly_member_id']) ? $post_data['kly_member_id'] : '';
        //恐龙园专属优惠券参数 1-恐龙园 2-认证中心
        if ($post_data['coupon_from'] == 1) {
            $extra['coupon_info']['coupons_type'] = isset($post_data['coupons_type']) ? $post_data['coupons_type'] : '';
            $extra['coupon_info']['couponid'] = isset($post_data['couponid']) ? $post_data['couponid'] : '';
            $extra['coupon_info']['couponname'] = isset($post_data['couponname']) ? $post_data['couponname'] : '';
            $extra['coupon_info']['discount'] = isset($post_data['discount']) ? $post_data['discount'] : '';
            $extra['guding_discount'] = isset($post_data['guding_discount']) ? $post_data['guding_discount'] : 1;
            $extra['coupon_info']['coupon_from'] = $post_data['coupon_from'];

        } elseif ($post_data['coupon_from'] == 2) {
            $extra['coupon_info']['coupons_type'] = isset($post_data['coupons_type']) ? $post_data['coupons_type'] : '';
            $extra['coupon_info']['couponid'] = isset($post_data['couponid']) ? $post_data['couponid'] : '';
            $extra['coupon_info']['couponname'] = isset($post_data['couponname']) ? $post_data['couponname'] : '';
            $extra['coupon_info']['discount'] = isset($post_data['discount']) ? $post_data['discount'] : '';
            $extra['coupon_info']['coupon_from'] = $post_data['coupon_from'];
        }

        //恐龙园优惠券参数
        if ($extra['coupon_info']['coupon_from'] == 1) {
            if ($extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid'] && $extra['coupon_info']['discount']) {
                $coupons_type = $extra['coupon_info']['coupons_type'];
                if ($coupons_type == 1) {
                    $discount_column = isset($extra['coupon_info']['discount']) ? (($extra['coupon_info']['discount']) / 100) : 1;
                    if ($discount_column) {
                        $pay_price = ($total_price * $extra['guding_discount']) * $discount_column;
                        $discount = $total_price - $pay_price;
                    }
                }
                if ($coupons_type == 2 || $coupons_type == 3) {
                    $coupon_discount = isset($extra['coupon_info']['discount']) ? $extra['coupon_info']['discount'] : 0;
                    $pay_price = $total_price * $extra['guding_discount'] - $coupon_discount;
                    if ($pay_price < 0) {
                        $pay_price = 0;
                    }
                    $discount = $total_price - $pay_price;
                }
                $pay_price = sprintf('%.2f', $pay_price);
                if ($pay_price < 0) {
                    return [400, '金额有误'];
                }
            } else {
                $pay_price = $total_price * $extra['guding_discount'];
                $pay_price = sprintf('%.2f', $pay_price);
                $cartGoods['discount'] = $total_price - $pay_price;
                $cartGoods['pay_price'] = $pay_price;;
            }
        } elseif ($extra['coupon_info']['coupon_from'] == 2) {
            //除了恐龙园和德清的生成订单
            if ($extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid'] && $extra['coupon_info']['discount']) {
                $coupons_type = $extra['coupon_info']['coupons_type'];
                if ($coupons_type == 2) {
                    $discount_column = isset($extra['coupon_info']['discount']) ? (($extra['coupon_info']['discount']) / 100) : 1;
                    if ($discount_column) {
                        $pay_price = $total_price * $discount_column;
                        $discount = $total_price - $pay_price;
                    }
                }
                if ($coupons_type == 1 || $coupons_type == 3) {
                    $coupon_discount = isset($extra['coupon_info']['discount']) ? $extra['coupon_info']['discount'] : 0;
                    $pay_price = $total_price - $coupon_discount;
                    if ($pay_price < 0) {
                        $pay_price = 0;
                    }
                    $discount = $total_price - $pay_price;
                }
                $pay_price = sprintf('%.2f', $pay_price);
                if ($pay_price < 0) {
                    return [400, '金额有误'];
                }
                $cartGoods['pay_price'] = $pay_price;
                $cartGoods['discount'] = $discount;
            } else {
                $pay_price = $total_price;
                $pay_price = sprintf('%.2f', $pay_price);
                $cartGoods['pay_price'] = $pay_price;
                $cartGoods['discount'] = 0;
            }
        }
        $transaction = Yii::$app->db->beginTransaction();


        //保存订单到数据库
        $order_sn = CommonFun::makeRandSn($this->member_id);
        $model = New OrdersModel();
        $model->appid = $appid;
        $model->member_id = $this->member_id;
        $model->order_sn = $order_sn;
        $model->price = $total_price;
        $model->pay_price = $pay_price;
        $model->name = $post_data['name'];
        $model->phone = $post_data['phone'];
        $model->ratecode = $post_data['ratecode'];
        $model->rmtype = $post_data['rmtype'];
        $model->des = $post_data['des'];
        $model->rate = $post_data['rate'];
        $model->rmnum = $post_data['rmnum'];
        $model->arr = $post_data['arr'];
        $model->dep = $post_data['dep'];
        $model->pkg = $post_data['pkg'];
        $model->kly_member_id = $extra['kly_member_id'];
        $model->discount = $discount;
        $model->coupons_type = $extra['coupon_info']['coupons_type'];
        $model->couponid = $extra['coupon_info']['couponid'];
        $model->couponname = $extra['coupon_info']['couponname'];
        $model->coupon_from = $extra['coupon_info']['coupon_from'];
        $model->order_ddetail = json_encode($arr_temp[0]['dailyrates']);
        $model->order_state = 1;
        $model->create_time = date('Y-m-d H:i:s');
        $model->payment_code = isset($post_data['pay_type'])?$post_data['pay_type']:'weixin';

        if ($model->save()) {
            $orderId = $model->attributes['id'];
            //核销优惠券（恐龙园优惠券核销）
            if ($extra['coupon_info']['coupon_from'] == 1 && $extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid'] && $extra['coupon_info']['discount']) {
                $res = MemberServices::verify($extra['kly_member_id'], $extra['coupon_info']['couponid'], $extra['coupon_info']['couponname'], $orderId, $appid);
                if (!$res) {
                    $transaction->rollBack();
                    return Tool::showRes([400, '核销优惠券失败']);
                }
            }
            //核销优惠券（认证中心优惠券核销）
            if ($extra['coupon_info']['coupon_from'] == 2 && $extra['coupon_info']['coupons_type'] && $extra['coupon_info']['couponid'] && $extra['coupon_info']['discount']) {
                $res = AcServices::useCoupon($appid, $this->member_id, $extra['coupon_info']['couponid']);
                if (!$res) {
                    $transaction->rollBack();
                    return Tool::showRes([400, '核销优惠券失败']);
                }
            }
            $transaction->commit();
            return Tool::showRes([0, '下单成功'], $order_sn);
        } else {

            return Tool::showRes([400, '下单失败']);
        }
    }
    /**
     * 腾讯地图坐标转百度地图坐标
     * @param [String] $lat1 A点的纬度
     * @param [String] $lng1 A点的经度
     * @param [String] $lat2 B点的纬度
     * @param [String] $lng2 B点的经度
     * @return [String] 两点坐标间的距离，输出单位为米
     */
    function getDistance($lat1, $lng1, $lat2, $lng2)

    {
        $EARTH_RADIUS = 6378.137;//地球的半径

        $radLat1 = $this->rad($lat1);

        $radLat2 = $this->rad($lat2);

        $a = $radLat1 - $radLat2;

        $b = $this->rad($lng1) - $this->rad($lng2);

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +

                cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));

        $s = $s * $EARTH_RADIUS;

        $s = round($s * 10000) / 10000;

        $s = $s * 1000;

        return ceil($s);

    }

    //百度地图坐标计算
    function rad($d)
    {
        return $d * 3.1415926535898 / 180.0;
    }


    public function rn_date($time)
    {
        $var = explode(' ', $time);
        $var1 = $var[0];
        $time = explode('-', $var1);
        if ($time[1] < 10) {
            $time[1] = str_replace("0", "", $time[1]);
        } else {
            $time[1] = $time[1];
        }
        if ($time[2] < 10) {
            $time[2] = str_replace("0", "", $time[2]);
        } else {
            $time[2] = $time[2];
        }
        $new_time = $time[1] . "月" . $time[2] . "日";
        return $new_time;
    }


    protected function recordData($options)
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . '/logs/hotel_ceshi' . date('Ymd') . '.log';
        $log->messages[] = [
            json_encode($options)
        ];
        $log->export();
    }
    /**
     * 期间日期
     * @param $startDate
     * @param $endDate
     * @return array
     */
    function periodDate($startDate, $endDate){
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $arr = array();
        while ($startTime <= $endTime){
            $arr[] = date('Y-m-d', $startTime);
            $startTime = strtotime('+1 day', $startTime);
        }
        return $arr;
    }
    //根据日期判断是否有天天特惠 并且返回价格
    public function actionCheckRoomTypeActivity($date, $rate, $rmtype)
    {
        $room_type_data = RoomType::find()->where("rmtype = '$rmtype'")->asArray()->one();
        $room_type_id = $room_type_data['id'];
        $res = RoomTypeActivityOff::find()->where("room_type_id = '$room_type_id' and date ='$date'")->asArray()->one();
        if ($res) {
            $data = RoomTypeActivity::find()->where("room_type_id = '$room_type_id'")->asArray()->one();
            if ($data['type'] == 1) {
                $arr['rate'] = round(($rate * $data['num']) / 10);
                $arr['label'] = $data['label'];
                $arr['type'] = 1;
                $arr['num'] = $data['num'];

            } else {
                $arr['rate'] = round($rate - $data['num']);
                $arr['label'] = $data['label'];
                $arr['type'] = 2;
                $arr['num'] = $data['num'];
            }
        } else {
            $arr['rate'] = $rate;
            $arr['label'] = '';
        }
        return $arr;
    }
}
